package com.gbase8c.dmt.model.migration.dto;

import com.gbase8c.dmt.model.enums.MigrationObjectType;
import com.gbase8c.dmt.model.enums.MigrationTaskStatus;
import com.gbase8c.dmt.model.enums.Status;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.*;
import java.util.stream.Collectors;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class PrecheckResult {
    private String id;
    private List<PrecheckRecord> records;
    private Date startTime;
    private Date endTime;
    private MigrationTaskStatus status;
    private String msg;


    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class PrecheckRecord {
        private String key;
        private MigrationObjectType type;
        private String schema;
        private String tableName;
        private String name;
        private List<String> contents;
        private List<String> customContents;
        private Status status;
        private String msg;
        private Boolean modified;
    }

    public void addRecord(PrecheckRecord record) {
        if (records == null) {
            records = new ArrayList<>();
        }
        records.add(record);
    }

    public Map<MigrationObjectType, List<PrecheckRecord>> typeRecords(List<MigrationObjectType> orders) {
        Map<MigrationObjectType, List<PrecheckRecord>> typeRecords = records.stream()
                .collect(Collectors.groupingBy(PrecheckRecord::getType));
        Map<MigrationObjectType, List<PrecheckRecord>> orderedTypeRecords = new LinkedHashMap<>();
        for (MigrationObjectType migrationObjectType : orders) {
            if (typeRecords.get(migrationObjectType) != null && !typeRecords.get(migrationObjectType).isEmpty()) {
                orderedTypeRecords.put(migrationObjectType, typeRecords.get(migrationObjectType));
            }
        }
        return orderedTypeRecords;
    }
}
